package com.xian.im.common.utils.bussiness;

import com.xian.im.common.exception.BusinessException;
import com.xian.im.common.model.session.SessionUser;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * @program: xian-code
 * @description:
 * @author: liru.xian
 * @create: 2021-01-25 19:51
 **/
public class ChannelUserContextUtil {

    public static SessionUser build(FullHttpRequest req){
        String uri = req.uri().replace( "/ws/", "");
        String[] split = uri.split("/");
        if (split.length == 6) {
            HttpHeaders headers = req.headers();
            String ip = headers.get("X-Real-IP");
            ip =  StringUtils.isNotBlank(ip)? ip : "127.0.0.1";
            // /{appKey}/{sign}/{account}/{channel}/{version}/{deviceId}
            StringBuilder sb = new StringBuilder();
            sb.append(split[0]).append(split[2]).append(split[3]).append(split[4]).append(split[5]);
            SessionUser param = SessionUser.builder()
                    .appKey(split[0])
                    .sign(split[1])
                    .account(split[2])
                    .channel(split[3])
                    .version(split[4])
                    .deviceId(split[5])
                    .realIp(ip)
                    .param(sb.toString())
                    .build();
            return param;
        }
        throw new BusinessException("参数格式错误");
    }
}
